package com.mystore.framework.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mystore.framework.mapper.UserMapper;
import com.mystore.framework.pojo.LoginUser;
import com.mystore.framework.pojo.Role;
import com.mystore.framework.pojo.User;
import icu.mhb.mybatisplus.plugln.core.JoinLambdaWrapper;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.security.auth.login.AccountLockedException;
import java.util.HashSet;
import java.util.Set;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        JoinLambdaWrapper<User> queryWrapper=new JoinLambdaWrapper<>(User.class);
        queryWrapper.leftJoin(Role.class,Role::getRoleId,User::getRoleId)
                .oneToOneSelect(User::getRole, Role.class)
                .end();
        QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
        System.err.println(username);
        userQueryWrapper.eq("user_email",username);
        queryWrapper.changeQueryWrapper(userQueryWrapper);
        User user=userMapper.joinSelectOne(queryWrapper,User.class);
        if (user == null) {
            throw new UsernameNotFoundException(username+" not found");
        }
        if(user.getEnabled()==0)
            throw new LockedException("您的帐户被锁定");
        Set<SimpleGrantedAuthority> authorities = new HashSet<>();
        if(user.getRole()!=null)
             authorities.add(new SimpleGrantedAuthority(user.getRole().getRoleId().toString()));
        return new LoginUser(user,authorities);
    }
}